from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
from base64 import b64encode
import redis
from .. import json
from .. import requests
from .. import time
from .. import random



class RedisSDK:

    rdb = None

    def __init__(self) -> None:
        super().__init__()
        self.rdb = redis.Redis(host='122.51.1.235',
                               port=7369, decode_responses=True)

    def set_value(self, key: str, val: str, timeout: int) -> None:
        '''
        缓存一个键值对并设置过期时间
        过期时间以秒为单位
        '''
        self.rdb.set(name=key, value=val, ex=timeout)

    def get_value(self, key: str) -> str:
        '''
        根据 key 获取键值对的 value
        '''
        return self.rdb.get(key)

    def do_save_to_set(self, key, value):
        '''
        保存到set中
        '''
        self.rdb.sadd(key, value)

    def delete(self, key):
        '''
        删除一个键
        '''
        self.rdb.delete(key)

    def send_messgae(self, title, message):
        '''
        推送消息
        '''
        self.rdb.publish(title, message)

    def delete_from_set(self, k, v):
        '''
        从set中移除
        '''
        self.rdb.srem(k, v)

    def get_all_like_key(self, p):
        '''
        获取所有符合条件的键
        '''
        return self.rdb.keys(pattern=p)

    def get_all_from_set(self, k):
        '''
        获取set
        '''
        return self.rdb.smembers(k)

    def get_set_size(self, k):
        '''
        获取set长度
        '''
        return self.rdb.scard(k)

    def get_random_value(self, key: str) -> str:
        '''
        从set中获取一个随机值
        '''
        return self.rdb.srandmember(key, 1)[0]

    def check_if_in_set(self, k, v):
        '''
        检查值是否在 set 中
        '''
        return self.rdb.sismember(k, v)